package order;


import beans.Car;
import cart.Cart;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "OrderProcessServlet", value = "/OrderProcessServlet")
public class OrderProcessServlet extends HttpServlet {
    private OrderService orderService = new OrderService();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        HttpSession session = request.getSession();
        List<Car> carList = (List<Car>) session.getAttribute("carList");




        String userId = ProcessUtil.getUserIdBySessionId(session);
            if (carList!=null){
                // 对生成订单进行事务控制
                String orderId = null;
                try {
                    Order order = new Order();
                    order = orderService.saveOrder(carList, userId);
                    JdbcUtil.commit();

                    session.setAttribute("orderId",orderId);
                    //response.getWriter().write(new Gson().toJson("success"));
                } catch (Exception e) {
                    // 如果出错事务回滚
                    JdbcUtil.rollback();
                    e.printStackTrace();
                }
            }


        if (carList==null){
            response.sendRedirect("first.jsp");
            return;
        }
        request.getRequestDispatcher("order.jsp").forward(request,response);



    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }
}

